package com.myzl.coal.webSocket;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.myzl.coal.domain.RealTimeData;
import com.myzl.coal.service.IRealTimeDataService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author jl
 * @since 2021/1/19 22:05
 */
@Component
@ServerEndpoint("/webSocket/{key}")
@Slf4j
@Data
public class WebSocket {

    private Session session;
    public static final ConcurrentHashMap<String, WebSocket> webSocketMap = new ConcurrentHashMap<>();
    private static IRealTimeDataService realTimeDataService;

    @Autowired
    public void setRealTimeDataService(IRealTimeDataService realTimeDataService){
        WebSocket.realTimeDataService = realTimeDataService;
    }
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "key") String key) {
        this.session = session;
        webSocketMap.put(key, this);

        RealTimeData params = new RealTimeData();
        List<RealTimeData> realTimeDataList = realTimeDataService.selectRealTimeDataList(params);

        JSONArray result = getResult(realTimeDataList);
        sendMessage(result.toJSONString(), key);

        log.info("【websocket消息】有新的连接【{}】, 总数:{}", key, webSocketMap.size());
    }

    @OnClose
    public void onClose(@PathParam(value = "key") String key) {
        webSocketMap.remove(key);
        log.info("【websocket消息】连接断开, 总数:{}", webSocketMap.size());
    }

    @OnMessage
    public void onMessage(String message, @PathParam(value = "key") String key) {
        log.info("【websocket消息】收到客户端【{}】发来的消息:{}", key, message);
    }
    @OnError
    public void onError(Session session, Throwable e) {
        log.info("Websocket error:", e);
    }
    /**
     * 指定用户发送
     */
    public void sendMessage(String message, String key) {
        log.debug("【websocket消息】发送指定消息, message={}, key={}", message, key);
        try {
            webSocketMap.get(key).session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 群发
     */
    public void sendMessage(String message) {
        log.debug("【websocket消息】广播消息, message={}", message);
        for (String key : webSocketMap.keySet()) {
            try {
                webSocketMap.get(key).session.getBasicRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public JSONArray getResult(List<RealTimeData> dataList) {
        JSONArray collect = dataList.stream().map(m -> {
            Integer deviceId = m.getDeviceId();
            Integer dictValue = m.getDictValue();
            int dataValue;
            try {
                dataValue = Double.valueOf(m.getDataValue()).intValue();
            } catch (Exception e) {
                dataValue = 0;
            }
            String dataUnit = m.getDataUnit();
            JSONObject json = getJsonObject(deviceId, dictValue, dataValue, dataUnit);
            return json;

        }).collect(
                JSONArray::new,
                JSONArray::add,
                (ja1, ja2) -> {
                    for (final Object o : ja2) {
                        ja1.add(o);
                    }
                }
        );
        return collect;
    }

    public JSONObject getJsonObject(Integer deviceId, Integer dictValue, int dataValue, String dataUnit) {
        String tag = deviceId + "_" + dictValue;
        String value = dataValue + dataUnit;
        JSONObject json = new JSONObject();
        json.put("tag", tag);
        json.put("text", value);
        json.put("value", value);
        return json;
    }
}
